package com.lenovo.smarttraffic.ui.fragment.stage4;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.CarInfo;
import com.lenovo.smarttraffic.bean.ChargeHistory;
import com.lenovo.smarttraffic.bean.UserBean;
import com.lenovo.smarttraffic.database.CarInfoBean;
import com.lenovo.smarttraffic.ui.adapter.UserCarRvAdapter;
import com.lenovo.smarttraffic.ui.adapter.UserChargeHistoryAdapter;
import com.lenovo.smarttraffic.ui.fragment.MyBaseFragment;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static android.content.Context.NOTIFICATION_SERVICE;

public class UserCenterFragment extends MyBaseFragment {

    private int type = 0;

    private View view;
    private Context context;

    private Gson gson = new Gson();

    private NotificationManager manager;

    private SharedPreferences preferences;

    private Handler handler = new Handler();

    public UserCenterFragment setType(int type) {
        this.type = type;
        return this;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        this.manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        this.preferences = context.getSharedPreferences(Constant.THRESHOLD, Context.MODE_PRIVATE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        switch (type) {
            case 0:
                view = inflater.inflate(R.layout.fragment_user_info, container, false);
                break;
            case 1:
                view = inflater.inflate(R.layout.fragment_charge_history, container, false);
                break;
            case 2:
                view = inflater.inflate(R.layout.fragment_user_threshold, container, false);
                break;
        }

        return view;
    }

    @Override
    public void onViewFinished() {
        switch (type) {
            case 0:
                initType1();
                break;
            case 1:
                initType2();
                break;
            case 2:
                initType3();
                break;
        }
    }

    private void initType1() {
        View avatar = view.findViewById(R.id.avatar);
        TextView name_tv = view.findViewById(R.id.name_tv);
        TextView sex_tv = view.findViewById(R.id.sex_tv);
        TextView phone_tv = view.findViewById(R.id.phone_tv);
        TextView id_tv = view.findViewById(R.id.id_tv);
        TextView time_tv = view.findViewById(R.id.time_tv);
        RecyclerView car_rv = view.findViewById(R.id.car_rv);

        HttpUtils.post("get_all_user_info", new HttpUtils().setParam("UserName", MainActivity.userName),
                response -> HttpUtils.post("get_car_info", new HttpUtils().setParam("UserName", MainActivity.userName),
                        response2 -> {
                            UserBean.ROWS_DETAIL user = gson.fromJson(response.toString(), UserBean.class).getROWS_DETAIL().get(1);
                            CarInfo carInfo = gson.fromJson(response2.toString(), CarInfo.class);
                            avatar.setBackgroundResource(user.getPsex().equals("男") ? R.mipmap.touxiang_2 : R.mipmap.touxiang_1);
                            name_tv.setText("姓名：" + user.getPname());
                            sex_tv.setText("性别：" + user.getPsex());
                            phone_tv.setText("手机号码：" + user.getPtel());
                            id_tv.setText("身份证号：" + user.getPcardid());
                            time_tv.setText("注册时间：" + user.getPregisterdate().split(" ")[0]);

                            List<CarInfoBean> carAllDBS = LitePal.findAll(CarInfoBean.class);
                            if (carAllDBS.size() == 0) {
                                for (int i = 0; i < carInfo.getROWS_DETAIL().size(); i++) {
                                    CarInfo.ROWSDETAILBean allcar = carInfo.getROWS_DETAIL().get(i);
                                    new CarInfoBean(allcar.getNumber(),
                                            allcar.getCarnumber(), allcar.getPcardid(),
                                            allcar.getBuydate(), allcar.getCarbrand()).save();
                                }
                            }
                            ArrayList<String[]> strings = new ArrayList<>();
                            //进行数据库读取
                            for (int i = 0; i < carAllDBS.size(); i++) {
                                if (carAllDBS.get(i).getPcardid().equals(carInfo.getROWS_DETAIL().get(1).getPcardid())) {
                                    String[] data = new String[3];
                                    data[0] = carAllDBS.get(i).getCarnumber();
                                    data[1] = carAllDBS.get(i).getCarbrand();
                                    data[2] = String.valueOf(carAllDBS.get(i).getNumber());
                                    strings.add(data);
                                }
                            }

                            car_rv.setAdapter(new UserCarRvAdapter(strings));
                        }));
    }


    private void initType2() {
        View avatar = view.findViewById(R.id.avatar);
        TextView name_tv = view.findViewById(R.id.name_tv);
        TextView money_tv = view.findViewById(R.id.money_tv);
        ListView listView = view.findViewById(R.id.listView);

        HttpUtils.post(context, "get_all_user_info",
                new HttpUtils().setParam("UserName", MainActivity.userName),
                response -> HttpUtils.post(context, "get_car_info",
                        new HttpUtils().setParam("UserName", MainActivity.userName),
                        response2 -> HttpUtils.post(context, "get_car_account_record",
                                new HttpUtils().setParam("UserName", MainActivity.userName),
                                response3 -> {
                                    UserBean user = gson.fromJson(response.toString(), UserBean.class);
                                    UserBean.ROWS_DETAIL rowsDetail = user.getROWS_DETAIL().get(1);
                                    CarInfo carInfo = gson.fromJson(response2.toString(), CarInfo.class);
                                    ChargeHistory chargeHistory = gson.fromJson(response3.toString(), ChargeHistory.class);
                                    avatar.setBackgroundResource(rowsDetail.getPsex().equals("男") ? R.mipmap.touxiang_2 : R.mipmap.touxiang_1);
                                    name_tv.setText(rowsDetail.getPname());

                                    List<ChargeHistory.ROWSDETAILBean> list = chargeHistory.getROWS_DETAIL();
                                    int money = 0;
                                    for (int i = 0; i < 5; i++) {
                                        money += list.get(i).getMoney();
                                    }
                                    money_tv.setText(5 * 200 + ".00");

                                    listView.setAdapter(new UserChargeHistoryAdapter(context, chargeHistory, user, carInfo));
                                })));
    }

    private void initType3() {
        TextView threshold_tv = view.findViewById(R.id.threshold_tv);
        EditText money_et = view.findViewById(R.id.monet_et);
        Button set_btn = view.findViewById(R.id.set_btn);
        threshold_tv.setText(String.format("当前1-4号小车账户余额警告阈值为%s元", preferences.getString(Constant.ts_1_4, "当前 1-4 号小车账户余额告警阈值未设置！")));
        money_et.setText(preferences.getString(Constant.ts_1_4, ""));
        set_btn.setOnClickListener(v -> {
            if (money_et.getText().toString().isEmpty()) {
                ToastUtils.showToast(context, "请输入阈值");
            } else {
                preferences.edit().putString(Constant.ts_1_4, money_et.getText().toString()).apply();
                threshold_tv.setText(String.format("当前1-4号小车账户余额警告阈值为%s元", money_et.getText().toString()));
                ToastUtils.showToast(context, "设置成功");
            }
        });

        runnable.run();
        refresh();
    }

    private void refresh() {
        handler.postDelayed(() -> {
            runnable.run();
            refresh();
        }, 3000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int ts_level = Utils.parseInt(preferences.getString(Constant.ts_1_4, "-1"));

            for (int i = 1; i < 5; i++) {
                int finalI = i;
                HttpUtils.post(context, "get_car_account_balance",
                        new HttpUtils().setParam("CarId", i)
                                .setParam("UserName", MainActivity.userName),
                        response -> {
                            Map responseMap = new Gson().fromJson(response.toString(), Map.class);
                            int money = (int) Utils.parseDouble(responseMap.get("Balance").toString());

                            if (manager != null && money < ts_level) {
                                NotificationCompat.Builder builder;
                                int channelId = 2;
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Android 8.0适配
                                    NotificationChannel channel = new NotificationChannel(String.valueOf(channelId),
                                            "余额阈值警告", NotificationManager.IMPORTANCE_HIGH);
                                    manager.createNotificationChannel(channel);
                                    builder = new NotificationCompat.Builder(context, String.valueOf(channelId));
                                } else {
                                    builder = new NotificationCompat.Builder(context);
                                }
                                builder.setContentTitle("余额阈值警告")
                                        .setContentText("车辆号：" + finalI + " 余额：" + money + " 阈值：" + ts_level)
                                        .setWhen(System.currentTimeMillis())
                                        .setSmallIcon(R.mipmap.car3)
                                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.car3));

                                Notification notification = builder.build();
                                //channelId为本条通知的id
                                manager.notify(channelId, notification);
                            }
                        });
            }
        }
    };
}
